package com.hl.toolkit.pay.controller;

import com.suning.PaymentOrderMain;
import com.suning.SuNingConfig;
import com.suning.demo.BatchWithdrawDemo;
import com.suning.demo.WithdrawQueryDemo;
import com.suning.dto.CardInfoDto;
import com.suning.epp.demo.SuningH5Pay;
import com.suning.util.Util;
import com.tycoin.account.slaveentity.*;
import com.tycoin.account.slaveservice.*;
import com.tycoin.common.entity.SuningPaymentInfo;
import com.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 支付宝支付
 */
@Controller
@RequestMapping(value = { "/interface/suningPay" })
public class SuNingPayController {

	private static final Logger logger = LoggerFactory.getLogger(SuNingPayController.class);

	@Autowired
	private TycoinAccountPaymentService tycoinAccountPaymentService;
	@Autowired
	private TycoinAccountRechargeService tycoinAccountRechargeService;
	@Autowired
	private TycoinAccountService tycoinAccountService;
	@Autowired
	private TycoinEtcLogService tycoinEtcLogService;
	@Autowired
	private TycoinAccountCashService tycoinAccountCaseService;
	@Autowired
	private TycoinAccountRechargeCallbackProcessService tycoinAccountRechargeCallbackProcessService;

	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/withdrawPay", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String withdrawPay(HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		String snPaymentSwitch = LoadProperties.loadPropertiesValue("snPaymentSwitch");
		System.out.println("开关状态：" + snPaymentSwitch);
		if ("1".equals(snPaymentSwitch)) {
			String receiverName = request.getParameter("receiverName");
			String amount = request.getParameter("amount");
			String bankName = request.getParameter("bankName");
			String receiverCardNo = request.getParameter("receiverCardNo");
			String bankCode = request.getParameter("bankCode");
			String batchNo = request.getParameter("batchNo");
			String addip = IpRequestUtils.getRemoteHost(request);

			SuningPaymentInfo suningPaymentInfo = new SuningPaymentInfo();

			suningPaymentInfo.setAmount(amount);

			suningPaymentInfo.setBankCode(bankCode);
			suningPaymentInfo.setBankName(bankName);
			suningPaymentInfo.setReceiverCardNo(receiverCardNo);
			suningPaymentInfo.setAddip(addip);

			BatchWithdrawDemo batchWithdrawDemo = new BatchWithdrawDemo();
			if (StringUtil.isNull(batchNo)) {
				batchNo = Util.generalBatchNo();
			}
			String Logno = request.getParameter("Logno");

			System.out.println("----------批次号:" + batchNo + "-----------");
			TycoinAccountPayment tycoinAccountPayment = new TycoinAccountPayment();
			tycoinAccountPayment.setAddip(suningPaymentInfo.getAddip());
			tycoinAccountPayment.setAmount(amount);
			tycoinAccountPayment.setAmountFloat((float) Integer.parseInt(amount) / 100);
			tycoinAccountPayment.setBankCode(bankCode);
			tycoinAccountPayment.setCreateTime(new Date());
			tycoinAccountPayment.setDateTime(Long.valueOf(System.currentTimeMillis()));
			tycoinAccountPayment.setStatus(0);

			if (StringUtil.isNotNull(Logno)) {
				tycoinAccountPayment.setLogno(Logno);
			} else {
				Logno = RandomUtils.getRandomString(16);
				tycoinAccountPayment.setLogno(Logno);
			}

			tycoinAccountPayment.setPaymentId(batchNo);

			// 商家异步回调地址，可为空
			String suningPayNotifUrl = request.getParameter("suningPayNotifUrl");
			if (!StringUtil.isNull(suningPayNotifUrl)) {
				try {
					tycoinAccountPayment.setShopNotifUrl(URLDecoder.decode(suningPayNotifUrl, "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}

			tycoinAccountPaymentService.save(tycoinAccountPayment);

			try {

				result = batchWithdrawDemo.action(receiverName, amount, bankName, receiverCardNo, bankCode, batchNo);
				tycoinAccountPayment.setReturnText(result);
				JSONObject resuleJson = JSONObject.fromObject(result);
				JSONObject respArr = JSONObject.fromObject(resuleJson.get(SuNingConfig.merchantNo + "_" + batchNo));
				String responseCode = "";
				if (respArr != null && respArr.size() > 0) {
					responseCode = respArr.getString("responseCode");
				} else {
					responseCode = resuleJson.getString("responseCode");
					respArr = resuleJson;
				}

				if ("0000".equals(responseCode)) {

				} else {
					tycoinAccountPayment.setStatus(2);
					tycoinAccountPaymentService.save(tycoinAccountPayment);

				}
				respArr.put("batchNo", batchNo);
				respArr.put("Logno", Logno);
				result = respArr.toString();
			} catch (Throwable e) {
				tycoinAccountPayment.setStatus(3);
				tycoinAccountPaymentService.save(tycoinAccountPayment);
			}
		} else {
			result = "{code:\"NOTICE\",resultMessage:\"对不起，苏宁打款通道已关闭\"}";
		}
		return result;

	}

	/**
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/suningH5Pay", produces = "application/json;charset=UTF-8")
	public void suningH5Pay(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String result = "";
		Map<String, String> pageMap = new HashMap<String, String>();
		Random random = new Random();
		response.setContentType("text/html;charset=gbk");  
		response.setHeader("content-type","text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String outOrderNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + random.nextInt(99999);
		String orderAmount = request.getParameter("orderAmount");
		String price = request.getParameter("orderAmount");
		String userId = request.getParameter("userId");

		long dateTime = System.currentTimeMillis();
		String outTradeNo = String.valueOf(dateTime) + String.valueOf((long) (Math.random() * 1000000000L));

		TycoinAccountRecharge tycoinAccountRecharge = new TycoinAccountRecharge();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowDate = format.format(dateTime);

		tycoinAccountRecharge.setDateTime(dateTime);
		tycoinAccountRecharge.setPaymentTime(nowDate);
		tycoinAccountRecharge.setPaymentId(outTradeNo);
		tycoinAccountRecharge.setPayMode(6);

		String Logno = request.getParameter("Logno");
		if (!StringUtil.isNull(Logno)) {
			tycoinAccountRecharge.setLogno(Logno);
		} else {
			tycoinAccountRecharge.setLogno(RandomUtils.getRandomString(16));
		}
		String isMycharge = request.getParameter("isMycharge");
		if ("1".equals(isMycharge)) {
			tycoinAccountRecharge.setIsMycharge(1);
		}
		tycoinAccountRecharge.setPaymentId(outTradeNo);
		tycoinAccountRecharge.setFee("0");
		tycoinAccountRecharge.setIsOnline("0");
		tycoinAccountRecharge.setMoney(orderAmount);
		tycoinAccountRecharge.setMoneyfloat(((float) Integer.valueOf(orderAmount)) / 100);
		tycoinAccountRecharge.setUserId(userId);
		tycoinAccountRechargeService.save(tycoinAccountRecharge);

		pageMap.put("outOrderNo", outOrderNo);
		pageMap.put("orderAmount", orderAmount);
		pageMap.put("goodsName", "万众汇聚支付");
		pageMap.put("price", price);
		pageMap.put("body", "万众汇聚");
		try {
 			result = SuningH5Pay.buildRequest(pageMap);
			response.getWriter().write(result);
		} catch (Throwable e) {
			e.getMessage();
		}
 
	}
	
	/**
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/suningWithholdPay", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String suningWithholdPay(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		PaymentOrderMain paymentOrderMain=new PaymentOrderMain();
		
		   CardInfoDto buildCardInfo =new CardInfoDto();
		    String result=paymentOrderMain.GotoPay(buildCardInfo,"万众汇聚","10");
 		    
		    return result;
		 
	}

	@RequestMapping(value = "/queryWithdrawPay", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String queryWithdrawPay(HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		String batchNo = request.getParameter("batchNo");
		WithdrawQueryDemo withdrawQueryDemo = new WithdrawQueryDemo();
		try {
			result = withdrawQueryDemo.action(batchNo);
			JSONObject json = JSONObject.fromObject(result);
			if ("0000".equals(json.get("responseCode"))) {
				JSONObject contentJson = (JSONObject) json.get("content");
				JSONArray transferOrdersJosn = (JSONArray) contentJson.get("transferOrders");
				JSONObject transferOrdersArray = (JSONObject) transferOrdersJosn.get(0);
				String state = transferOrdersArray.get("success") + "";
				if ("true".equals(state)) {
					json.put("code", state);
					json.put("resultMessage", "支付成功");
				} else if ("false".equals(state)) {
					json.put("code", state);
					json.put("resultMessage", "支付失败," + transferOrdersArray.get("errMessage"));
				} else if ("processing".equals(state)) {
					json.put("code", state);
					json.put("resultMessage", "银行处理中");
				}
				json.put("returnMessage", "查询成功");
				result = json.toString();
			} else if ("2081".equals(json.get("responseCode"))) {
				result = "{\"code\":\"" + json.get("responseCode") + "\",\"returnMessage\":\"" + json.get("responseMsg")
						+ "\"}";
			} else if ("2080".equals(json.get("responseCode"))) {
				result = "{\"code\":\"" + json.get("responseCode") + "\",\"returnMessage\":\"查询失败\"}";
			}
		} catch (Throwable e) {
		}
		return result;
	}

	@RequestMapping(value = "/notiy_return", produces = "application/json;charset=UTF-8")
	public void notiy_return(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("------------我已经进入了notiy_return异步回调时间:" + System.currentTimeMillis() + "----------");
		String content = request.getParameter("content");
		System.out.println("------------content:" + content + "----------");
		// {"totalNum":1,"successNum":0,"dataSource":"00","failNum":1,"merchantNo":"70164071","transferOrders":[{"receiverCardNo":"6230583000003598756","errMessage":"调出款服务返回受理失败","success":"false","refundTicket":"N","bankName":"平安银行","bankCity":"","receiverType":"PERSON","bankCode":"PCB","bankProvince":"","poundage":100,"serialNo":"HQ5850105548","amount":1,"receiverName":"徐炼","id":1705280000000126681,"payeeBankLinesNo":""}],"status":"07","merchantName":"上海煌亦全贸易有限公司","poundage":100,"failAmount":1,"batchNo":"HQ8548202352","successAmount":0,"totalAmount":1}
		if (StringUtils.isNotBlank(content)) {
			JSONObject resuleJson = JSONObject.fromObject(content);
			String transferOrders = resuleJson.getString("transferOrders").replace("[", "").replace("]", "");
			JSONObject JsonTransferOrders = JSONObject.fromObject(transferOrders);
			String success = String.valueOf(JsonTransferOrders.get("success"));
			String batchNo = String.valueOf(JsonTransferOrders.get("serialNo"));
			String amount = String.valueOf(JsonTransferOrders.get("amount"));
			String status = String.valueOf(resuleJson.get("status"));
			String errorCode = String.valueOf(resuleJson.get("errorCode"));
			String errMessage = "";
			System.out.println("----------------------订单批次号：" + batchNo);
			TycoinAccountPayment tycoinAccountPayment = tycoinAccountPaymentService.findOneBypaymentId(batchNo);

			if ("false".equals(success)) {
				errMessage = String.valueOf(JsonTransferOrders.get("errMessage"));
				if (tycoinAccountPayment != null) {
					tycoinAccountPayment.setStatus(5);
					tycoinAccountPayment.setReturnText(content);
					tycoinAccountPaymentService.save(tycoinAccountPayment);
				}
				TycoinAccountCash accountCash = tycoinAccountCaseService.findOneBylogno(batchNo);
				if (accountCash != null) {
					accountCash.setStatus(5);
					tycoinAccountCaseService.save(accountCash);
				}

			} else {
				errMessage = "SUCCESS";
				TycoinAccountCash accountCash = tycoinAccountCaseService.findOneBylogno(batchNo);
				TycoinAccount tycoinAccount = tycoinAccountService.findOneByuserId(tycoinAccountPayment.getUserId());
				System.out.println("----------------------提现列表查询准备数据------");
				if (tycoinAccountPayment != null && tycoinAccountPayment.getStatus()!= 1) {
					if (tycoinAccountPayment != null) {
						tycoinAccountPayment.setStatus(1);

						tycoinAccountPayment.setReturnText(content);
						tycoinAccountPaymentService.save(tycoinAccountPayment);
					}
					if (accountCash != null && tycoinAccount != null) {
						System.out.println("----------------------查询账户表数据------：" + tycoinAccountPayment.getUserId());
						// 插入提现日志记录表
						System.out.println("----------------插入提现日志记录表：BEGIN");
						Float money = ((float) Integer.parseInt(amount)) / 100;// 分转换元
						BigDecimal countResult = AmountUtil.sub(String.valueOf(tycoinAccount.getUseMoney()), String.valueOf(money));
						TycoinEtcLog etcLog = new TycoinEtcLog();
						etcLog.setUserId(Integer.parseInt(tycoinAccountPayment.getUserId()));
						etcLog.setOldNum((AmountUtil.quzheng(String.valueOf(tycoinAccount.getUseMoney()))).floatValue());
						etcLog.setNum(-money);
						etcLog.setNewNum(countResult.floatValue());
						etcLog.setAddip("127.0.0.1");
						etcLog.setRemark(
								"佣金提现,会员[" + tycoinAccountPayment.getUserId() + "]本次提现：" + String.valueOf(money) + "元");
						tycoinEtcLogService.save(etcLog);
						System.out.println("----------------插入提现日志记录表：SUCCESS");
						// 修改账户佣金
						System.out.println("----------------修改账户佣金：BEGIN");
						System.out.println("----------------修改后的佣金余额：" + countResult.toString());

						tycoinAccount.setUseMoney(new BigDecimal(countResult.toString()));
						tycoinAccountService.save(tycoinAccount);
						System.out.println("----------------修改账户佣金：SUCCESS");
						// 修改提现表状态为成功
						System.out.println("----------------修改提现表状态：BEGIN");
						accountCash.setStatus(1);
						String mationMoney = (((float) Integer.parseInt(amount)) / 100) + "";
						accountCash.setRealMoney(AmountUtil.quzheng(mationMoney));
						tycoinAccountCaseService.save(accountCash);
						System.out.println("----------------修改提现表状态：SUCCESS");
					}
				}

			}
			String resultMessage = "";
			if ("true".equals(success)) {
				resultMessage = "支付成功";
			} else if ("false".equals(success)) {
				resultMessage = "支付失败," + JsonTransferOrders.get("errMessage");
			} else if ("processing".equals(success)) {
				resultMessage = "银行处理中";
			}
			if (tycoinAccountPayment != null) {
				// 开始异步回调
				String shopNotifUrl = tycoinAccountPayment.getShopNotifUrl();
				if (StringUtil.isNotNull(shopNotifUrl)) {
					System.out.println("开始异步回调：shopNotifUrl:" + shopNotifUrl + "&code=" + success + "&batchNo="
							+ tycoinAccountPayment.getPaymentId() + "&errorCode=" + errorCode + "&errMessage="
							+ errMessage);
					HttpClientUtils hct = new HttpClientUtils();
					hct.get(shopNotifUrl + "&code=" + success + "&batchNo=" + tycoinAccountPayment.getPaymentId()
							+ "&resultMessage=" + resultMessage);
				}
			}

		}
		System.out.println("------------content:" + content + "----------");
		try {
			response.getWriter().write("true");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/H5notiyReturn", produces = "application/json;charset=UTF-8")
	public void H5notiyReturn(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("------------我已经进入了H5notiyReturn异步回调时间:" + System.currentTimeMillis() + "----------");
		String content = request.getParameter("content");
		String result = "";

		String responseCode = request.getParameter("responseCode");

		String orders = request.getParameter("orders");
		JSONObject jsonobject = JSONObject.fromObject(orders);
		String outOrderNo = jsonobject.getString("outOrderNo");
		TycoinAccountRecharge tycoinAccountRecharge = tycoinAccountRechargeService.findOneBypaymentId(outOrderNo);
		if ("0000".equals(responseCode)) {
			if (tycoinAccountRecharge != null && tycoinAccountRecharge.getPaymentStatus() != 1) {
				tycoinAccountRecharge.setPaymentStatus(1);
				tycoinAccountRechargeService.save(tycoinAccountRecharge);
				tycoinAccountRechargeCallbackProcessService.rechargeCallbackProcess(tycoinAccountRecharge);
			}

		} else {
			tycoinAccountRecharge.setPaymentStatus(2);
			tycoinAccountRechargeService.save(tycoinAccountRecharge);
		}
		System.out.println("------------responseCode:" + responseCode + "----------");
		System.out.println("------------orders:" + orders + "----------");
		try {
			response.getWriter().write("true");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
